package com.shenyue.nbtownlet.activity;

import android.content.Context;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.os.Handler;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.hitomi.glideloader.GlideImageLoader;
import com.hitomi.tilibrary.style.progress.ProgressPieIndicator;
import com.hitomi.tilibrary.transfer.TransferConfig;
import com.hitomi.tilibrary.transfer.Transferee;
import com.shenyue.nbtownlet.R;
import com.shenyue.nbtownlet.base.BaseActivity;
import com.shenyue.nbtownlet.bean.Video;
import com.shenyue.nbtownlet.databinding.ActivityDoTaskDetailBinding;
import com.shenyue.nbtownlet.databinding.VideoPartItemBinding;
import com.shenyue.nbtownlet.event.BaseListener;
import com.shenyue.nbtownlet.model.AppInsertTaskModel;
import com.shenyue.nbtownlet.model.DefaultModel;
import com.shenyue.nbtownlet.util.DensityUtil;
import com.shenyue.nbtownlet.util.GlideUtil;
import com.shenyue.nbtownlet.util.StringUtil;
import com.trycatch.mysnackbar.Prompt;
import com.trycatch.mysnackbar.TSnackbar;
import com.xiao.nicevideoplayer.NiceVideoPlayer;
import com.xiao.nicevideoplayer.NiceVideoPlayerController;
import com.xiao.nicevideoplayer.NiceVideoPlayerManager;

import java.util.ArrayList;
import java.util.List;

/**
 * 已办任务
 */

public class DoTaskDetailActivity extends BaseActivity implements BaseListener {
    private ActivityDoTaskDetailBinding binding;
    private Transferee transferee;
    private Context mContext;
    private Handler mHandler = new Handler();
    private int[] wh;
    private JSONObject dataSource;
    private TSnackbar snackBar;
    private JSONObject flowData;

    private List<ImageView> mList = new ArrayList<>();
    private ArrayList<String> images = new ArrayList<>();
    private ArrayList<ImageView> afterImages = new ArrayList<>();
    private ArrayList<String> afterList = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        binding = DataBindingUtil.setContentView(this, R.layout.activity_do_task_detail);
        Bundle bundle = getIntent().getExtras();
        dataSource = JSON.parseObject(bundle.getString(DefaultModel.PAGE_DATA));
        String title = dataSource.getString("Title");
        if(StringUtil.isNull(title))
            title = dataSource.getString("TITILE");
        setActionBar(true, title);

        mContext = this;
        transferee = Transferee.getDefault(mContext);

        wh = DensityUtil.getWH(this, 2, 24);

        snackBar = showTSnackbar("正在查询数据..., 请稍候");
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                findDetail();
            }
        }, 32);
    }

    private void findDetail() {
        JSONObject param = new JSONObject();
        String InstanceID = dataSource.getString("InstanceID");
        if(StringUtil.isNull(InstanceID))
            InstanceID = StringUtil.dTs(dataSource.getString("ID"));
        param.put("id", InstanceID);
        AppInsertTaskModel.getDetailWorkByID(mContext, param, this);
    }

    private void initView() {
        binding.TASKCODE.setText(StringUtil.getValue(flowData.getString("CODE")));
        binding.TITILE.setText(StringUtil.getValue(flowData.getString("TITILE")));
        binding.TADDRESS.setText(StringUtil.getValue(flowData.getString("TADDRESS")));
        binding.ASSESSTASKNAME.setText(StringUtil.getValue(flowData.getString("ASSESSTASKNAME")));
        binding.ASSESSTYPENAME.setText(StringUtil.getValue(flowData.getString("ASSESSTYPENAME")));
        binding.AFTERIDEA.setText(StringUtil.getValue(flowData.getString("AFTERIDEA")));
        binding.SCORE.setText(flowData.getString("SCORE"));
        binding.PROBLEM.setText(StringUtil.getValue(flowData.getString("PROBLEM")));
        String CREATETIME = StringUtil.getValue(flowData.getString("CREATETIME"));
        if (CREATETIME.contains("T"))
            CREATETIME = CREATETIME.substring(0, CREATETIME.indexOf("T"));
        binding.CREATETIME.setText(CREATETIME);
        binding.CREATORNAME.setText(StringUtil.getValue(flowData.getString("CREATORNAME")));
        binding.ASSESSMENTNAME.setText(StringUtil.getValue(flowData.getString("ASSESSMENTNAME")));

        resetImages();
        resetVideos();
    }

    private void resetImages() {
        String IMAGEADDRESS = StringUtil.getValue(flowData.getString("IMAGEADDRESS"));
        if (!StringUtil.isNull(IMAGEADDRESS)) {
            String[] array = IMAGEADDRESS.split(",");
            for (int i = 0, j = array.length; i < j; i++) {
                images.add(array[i]);
            }
            binding.imageA.removeAllViews();
            for (int i = 0; i < images.size(); i++) {
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(wh[0], wh[1]);
                ImageView imageView = new ImageView(mContext);
                imageView.setId(i);
                imageView.setLayoutParams(layoutParams);
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TransferConfig config = TransferConfig.build()
                                .setNowThumbnailIndex(v.getId())
                                .setSourceImageList(images)
                                .setMissPlaceHolder(R.mipmap.ic_empty_photo)
                                .setOriginImageList(mList)
                                .setProgressIndicator(new ProgressPieIndicator())
                                .setImageLoader(GlideImageLoader.with(mContext.getApplicationContext()))
                                .create();
                        transferee.apply(config).show(new Transferee.OnTransfereeStateChangeListener() {
                            @Override
                            public void onShow() {
                                Glide.with(mContext).pauseRequests();
                            }

                            @Override
                            public void onDismiss() {
                                Glide.with(mContext).resumeRequests();
                            }
                        });
                    }
                });
                binding.imageA.addView(imageView);
                mList.add(imageView);
                GlideUtil.loadImgCenterCrop(mContext, images.get(i), imageView);
            }
        }
        String AFTERIMAGES = StringUtil.getValue(flowData.getString("AFTERIMAGES"));
        if (!StringUtil.isNull(AFTERIMAGES)) {
            String[] array = AFTERIMAGES.split(",");
            for (int i = 0, j = array.length; i < j; i++) {
                afterList.add(array[i]);
            }
            binding.imageB.removeAllViews();
            for (int i = 0; i < afterList.size(); i++) {
                LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(wh[0], wh[1]);
                ImageView imageView = new ImageView(mContext);
                imageView.setId(i);
                imageView.setLayoutParams(layoutParams);
                imageView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        TransferConfig config = TransferConfig.build()
                                .setNowThumbnailIndex(v.getId())
                                .setSourceImageList(afterList)
                                .setMissPlaceHolder(R.mipmap.ic_empty_photo)
                                .setOriginImageList(afterImages)
                                .setProgressIndicator(new ProgressPieIndicator())
                                .setImageLoader(GlideImageLoader.with(mContext.getApplicationContext()))
                                .create();
                        transferee.apply(config).show(new Transferee.OnTransfereeStateChangeListener() {
                            @Override
                            public void onShow() {
                                Glide.with(mContext).pauseRequests();
                            }

                            @Override
                            public void onDismiss() {
                                Glide.with(mContext).resumeRequests();
                            }
                        });
                    }
                });
                binding.imageB.addView(imageView);
                afterImages.add(imageView);
                GlideUtil.loadImgCenterCrop(mContext, afterList.get(i), imageView);
            }
        }
    }

    private void resetVideos() {
        String MOIVEADDRESS = StringUtil.getValue(flowData.getString("MOIVEADDRESS"));
        if (!StringUtil.isNull(MOIVEADDRESS)) {
            List<Video> videoList = new ArrayList<>();
            String[] array = MOIVEADDRESS.split(",");
            for (int i = 0, j = array.length; i < j; i++) {
                videoList.add(new Video("", "", array[i]));
            }
            binding.videoA.removeAllViews();
            for (int i = 0, j = videoList.size(); i < j; i++) {
                binding.videoA.addView(getVideoPartItemBinding(videoList.get(i)));
            }
        }
        String AFTERMOIVE = StringUtil.getValue(flowData.getString("AFTERMOIVE"));
        if (!StringUtil.isNull(AFTERMOIVE)) {
            List<Video> videoList = new ArrayList<>();
            String[] array = MOIVEADDRESS.split(",");
            for (int i = 0, j = array.length; i < j; i++) {
                videoList.add(new Video("", "", array[i]));
            }
            binding.videoB.removeAllViews();
            for (int i = 0, j = videoList.size(); i < j; i++) {
                binding.videoB.addView(getVideoPartItemBinding(videoList.get(i)));
            }
        }
    }

    private View getVideoPartItemBinding(Video video) {
        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(wh[0], wh[1]);
        VideoPartItemBinding binding = DataBindingUtil.inflate(LayoutInflater.from(mContext), R.layout.video_part_item, null, false);
        binding.niceVideoPlayer.setPlayerType(NiceVideoPlayer.PLAYER_TYPE_IJK);
        binding.niceVideoPlayer.setUp(video.getVideoUrl(), null);
        NiceVideoPlayerController mController = new NiceVideoPlayerController(mContext);
        mController.setTitle(video.getTitle());
        mController.setImage(video.getImageUrl());
        binding.niceVideoPlayer.setController(mController);
        View view = binding.getRoot();
        view.setLayoutParams(layoutParams);

        return view;
    }

    @Override
    public void onDestroy() {
        if (transferee != null)
            transferee.destroy();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        if (NiceVideoPlayerManager.instance().onBackPressd()) {
            return;
        }
        super.onBackPressed();
    }

    @Override
    public void success(String val, String action) {
        if (AppInsertTaskModel.GETDETAILWORKBYID_ACTION.equals(action)) {
            hideTSnackbar(snackBar, "数据查询成功");
            flowData = JSON.parseObject(val);
            initView();
        }
    }

    @Override
    public void error(String error, String action) {
        hideTSnackbar(snackBar, error, Prompt.WARNING);
    }
}
